<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联的维护任务ID" prop="maintenanceTaskId">
        <el-input
          v-model="queryParams.maintenanceTaskId"
          placeholder="请输入关联的维护任务ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="消耗的物料/备件ID" prop="materialId">
        <el-input
          v-model="queryParams.materialId"
          placeholder="请输入消耗的物料/备件ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料批次号" prop="batchId">
        <el-input
          v-model="queryParams.batchId"
          placeholder="请输入物料批次号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="实际消耗数量" prop="consumedQuantity">
        <el-input
          v-model="queryParams.consumedQuantity"
          placeholder="请输入实际消耗数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计量单位" prop="unitOfMeasure">
        <el-input
          v-model="queryParams.unitOfMeasure"
          placeholder="请输入计量单位"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="消耗发生时间" prop="consumptionTime">
        <el-date-picker clearable
          v-model="queryParams.consumptionTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择消耗发生时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="操作执行人员ID" prop="consumedBy">
        <el-input
          v-model="queryParams.consumedBy"
          placeholder="请输入操作执行人员ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="记录创建时间" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择记录创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['equipment-service:consumption:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equipment-service:consumption:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['equipment-service:consumption:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['equipment-service:consumption:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="consumptionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="备件消耗记录ID" align="center" prop="consumptionId" />
      <el-table-column label="关联的维护任务ID" align="center" prop="maintenanceTaskId" />
      <el-table-column label="消耗的物料/备件ID" align="center" prop="materialId" />
      <el-table-column label="物料批次号" align="center" prop="batchId" />
      <el-table-column label="实际消耗数量" align="center" prop="consumedQuantity" />
      <el-table-column label="计量单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="消耗发生时间" align="center" prop="consumptionTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.consumptionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作执行人员ID" align="center" prop="consumedBy" />
      <el-table-column label="消耗备注说明" align="center" prop="notes" />
      <el-table-column label="记录创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['equipment-service:consumption:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['equipment-service:consumption:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改维护备件消耗记录（跟踪维护任务中的物料使用情况）对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="consumptionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联的维护任务ID" prop="maintenanceTaskId">
          <el-select
              v-model="form.maintenanceTaskId"
              placeholder="请选择关联的维护任务"
              clearable
              filterable
              @change="handleTaskChange"
          >
          <el-option
              v-for="task in tasksStore.tasksList"
              :key="task.taskId"
              :label="`${task.taskId} (${task.taskType})`"
              :value="task.taskId"
          />
          </el-select>
        </el-form-item>
        <!-- 物料选择 -->
        <el-form-item label="物料/备件" prop="materialId">
          <el-select
              v-model="form.materialId"
              @change="handleMaterialChange"
              filterable
              clearable
              placeholder="请选择物料"
          >
            <el-option
                v-for="[id, batches] of batchStore.materialsMap"
                :key="id"
                :label="`${id} `"
                :value="id"
            />
          </el-select>
        </el-form-item>

        <!-- 批次选择 -->
        <el-form-item label="物料批次" prop="batchId">
          <el-select
              v-model="form.batchId"
              :disabled="!form.materialId"
              filterable
          >
            <el-option
                v-for="batch in batchStore.getBatchesByMaterial(form.materialId)"
                :key="batch.batchId"
                :label="`${batch.batchId} (剩余: ${batch.currentQuantity}${batch.unitOfMeasure})`"
                :value="batch.batchId"
            >
              <span>{{ batch.batchId }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
            生产: {{ batch.productionDate }} | 剩余: {{ batch.currentQuantity }}{{ batch.unitOfMeasure }}
          </span>
            </el-option>
          </el-select>
        </el-form-item>


        <!-- 消耗数量（带校验） -->
        <el-form-item label="实际消耗数量" prop="consumedQuantity">
          <el-input
              v-model.number="form.consumedQuantity"
              type="number"
              placeholder="请输入实际消耗数量"
              clearable
              @blur="validateQuantity"
          >
            <template #append>
      <span v-if="form.batchId">
        当前库存: {{ batchStore.getBatchById(form.batchId)?.currentQuantity || 0 }}
      </span>
            </template>
          </el-input>
        </el-form-item>

        <!-- 计量单位（自动填充） -->
        <el-form-item label="计量单位" prop="unitOfMeasure">
          <el-input v-model="form.unitOfMeasure" readonly />
        </el-form-item>

        <el-form-item label="消耗发生时间" prop="consumptionTime">
          <el-date-picker clearable
            v-model="form.consumptionTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择消耗发生时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="操作执行人员ID" prop="consumedBy">
          <el-input
              v-model="form.consumedBy"
              placeholder="自动填充"
              readonly
          />
        </el-form-item>
        <el-form-item label="消耗备注说明" prop="notes">
          <el-input v-model="form.notes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="记录创建时间" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择记录创建时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Consumption">
import { listConsumption, getConsumption, delConsumption, addConsumption, updateConsumption ,updateBatchQuantity} from "@/api/equipment-service/consumption"
import {useTasksStore} from "@/store/modules/equipmenttasks.js";
import useMaterialBatchStore from "@/store/modules/materialbatch.js";
import request from "@/utils/request.js";

const tasksStore = useTasksStore()
const batchStore = useMaterialBatchStore()
// 加载任务列表
onMounted(() => {
  tasksStore.fetchTasks()
  batchStore.fetchBatches()
})

// 当选择任务时，自动填充人员ID
function handleTaskChange(taskId) {
  if (taskId) {
    const selectedTask = tasksStore.tasksList.find(task => task.taskId === taskId)
    if (selectedTask) {
      form.value.consumedBy = selectedTask.assignedToUserId
    }
  } else {
    form.value.consumedBy = '' // 清空选择时重置
  }
}

// 物料选择处理
function handleMaterialChange(materialId) {
  if (!materialId) {
    form.value.batchId = ''
    form.value.unitOfMeasure = ''
    return
  }
  // 自动填充计量单位（取第一个批次的单位）
  const batches = batchStore.getBatchesByMaterial(materialId)
  if (batches.length > 0) {
    form.value.unitOfMeasure = batches[0].unitOfMeasure
  }
}
// 数量输入校验
function validateQuantity() {
  if (!form.value.materialId || !form.value.batchId) return

  const batch = batchStore.batchesList.find(
      b => b.batchId === form.value.batchId
  )

  if (batch && form.value.consumedQuantity) {
    const remaining = batch.currentQuantity - form.value.consumedQuantity
    if (remaining < 0) {
      proxy.$modal.msgError(`消耗数量超过库存！当前剩余: ${batch.currentQuantity}`)
    } else {
      proxy.$modal.msgSuccess(`剩余数量: ${remaining}`)
    }
  }
}
const { proxy } = getCurrentInstance()

const consumptionList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    maintenanceTaskId: null,
    materialId: null,
    batchId: null,
    consumedQuantity: null,
    unitOfMeasure: null,
    consumptionTime: null,
    consumedBy: null,
    notes: null,
    createdAt: null
  },
  rules: {
    maintenanceTaskId: [
      { required: true, message: "关联的维护任务ID不能为空", trigger: "blur" }
    ],
    materialId: [
      { required: true, message: "消耗的物料/备件ID不能为空", trigger: "blur" }
    ],
    batchId: [
      { required: true, message: '请选择批次', trigger: 'blur' }
    ],
    consumedQuantity: [
      { required: true, message: "实际消耗数量不能为空", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (!form.value.batchId) return callback();
          const batch = batchStore.getBatchById(form.value.batchId);
          if (batch && value > batch.currentQuantity) {
            callback(new Error(`不能超过当前库存 (${batch.currentQuantity})`));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    unitOfMeasure: [
      { required: true, message: "计量单位不能为空", trigger: "blur" }
    ],
    consumptionTime: [
      { required: true, message: "消耗发生时间不能为空", trigger: "blur" }
    ],
    createdAt: [
      { required: true, message: "记录创建时间不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询维护备件消耗记录（跟踪维护任务中的物料使用情况）列表 */
function getList() {
  loading.value = true
  listConsumption(queryParams.value).then(response => {
    consumptionList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    consumptionId: null,
    maintenanceTaskId: null,
    materialId: null,
    batchId: null,
    consumedQuantity: null,
    unitOfMeasure: null,
    consumptionTime: null,
    consumedBy: null,
    notes: null,
    createdAt: null
  }
  proxy.resetForm("consumptionRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.consumptionId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加维护备件消耗记录（跟踪维护任务中的物料使用情况）"
  // 从 Pinia 获取选中的任务信息
  const selectedTask = tasksStore.selectedTask

  // 自动填充关联的 maintenanceTaskId 和 consumedBy（操作执行人员ID）
  if (selectedTask) {
    form.value.maintenanceTaskId = selectedTask.taskId
    form.value.consumedBy = selectedTask.assignedToUserId
  }

}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _consumptionId = row.consumptionId || ids.value
  getConsumption(_consumptionId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改维护备件消耗记录（跟踪维护任务中的物料使用情况）"
  })
}

/** 提交按钮 */


async function submitForm() {
  try {
    await proxy.$refs["consumptionRef"].validate();

    const isEdit = !!form.value.consumptionId;
    const apiMethod = isEdit ? updateConsumption : addConsumption;

    const response = await apiMethod(form.value);
    if (response.code !== 200) throw new Error(response.msg || '操作失败');

    proxy.$modal.msgSuccess(isEdit ? "修改成功" : "新增成功");
    const batchIdNum = parseInt(form.value.batchId, 10);
    // 库存更新逻辑
    if (form.value.batchId) {
      const batch = batchStore.getBatchById(form.value.batchId);
      if (!batch) throw new Error("未找到对应批次信息");

      const remaining = batch.currentQuantity - form.value.consumedQuantity;
      if (remaining < 0) throw new Error(`消耗数量不能超过当前库存 (${batch.currentQuantity})`);

      try {
        await request({
          url: '/equipment-service/equipment/inventory/batchDtos',
          method: 'put',
          data: {
            materialId: form.value.materialId,
            batchId: form.value.batchId,
            currentQuantity: form.value.consumedQuantity,
            remainingQuantity: remaining
          }
        });

        // 使用store的方法更新本地状态
        batchStore.updateBatchQuantity(form.value.batchId, remaining);

        proxy.$modal.msgSuccess(`库存同步成功，剩余: ${remaining}${batch.unitOfMeasure}`);
      } catch (error) {
        throw new Error(`库存更新失败: ${error.response?.data?.msg || error.message}`);
      }
    }

    open.value = false;
    await getList();
  } catch (error) {
    console.error("提交失败:", error);
    proxy.$modal.msgError(error.message);
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _consumptionIds = row.consumptionId || ids.value
  proxy.$modal.confirm('是否确认删除维护备件消耗记录（跟踪维护任务中的物料使用情况）编号为"' + _consumptionIds + '"的数据项？').then(function() {
    return delConsumption(_consumptionIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('equipment-service/consumption/export', {
    ...queryParams.value
  }, `consumption_${new Date().getTime()}.xlsx`)
}

getList()
</script>
